/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ekuma.epos.bean.util.sale;

import com.openbravo.bean.Customer;
import com.openbravo.data.loader.LocalRes;
import com.openbravo.format.Formats;
import com.openbravo.bean.PaymentInfo;
import com.openbravo.bean.PaymentInfoMagcard;
import com.openbravo.bean.Tax;
import com.openbravo.bean.sales.Ticket;
import com.openbravo.bean.sales.TicketLine;
import com.openbravo.bean.shard.IncludeTaxs;
import com.openbravo.pos.util.RoundUtils;
import com.openbravo.pos.util.StringUtils;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 *
 * @author Administrator
 */
public class TicketHelper {

    private static DateFormat m_dateformat = new SimpleDateFormat("hh:mm");

    public static String getName(Ticket t, Object info) {
        StringBuilder name = new StringBuilder();

        if (t.getCustomerId() != null) {
            name.append(t.getCustomer().toString());
            name.append(" - ");
        }

        if (t.isGroupPayTicket()) {
            name.append(t.getProperty(Ticket.AUTOCREATE_NAME));
            name.append(" - ");
        }

        if (info == null) {
            if (t.getM_iTicketId() == 0) {
                name.append("(" + m_dateformat.format(t.getM_dDate()) + " " + Long.toString(t.getM_dDate().getTime() % 1000) + ")");
            } else {
                name.append(Integer.toString(t.getM_iTicketId()));
            }
        } else {
            name.append(info.toString());
        }

        if (getTotal(t) > 0 && t.getCustomerId() == null) {
            name.append("~" + printTotal(t));
        }

        return name.toString();
    }

    public static String getName(Ticket t) {
        return getName(t,null);
    }

    public static String printId(Ticket t) {
        if (t.getM_iTicketId() > 0) {
            // valid ticket id
            return Formats.INT.formatValue(t.getM_iTicketId());
        } else {
            return "";
        }
    }

    public static String printDate(Ticket t) {
        return Formats.TIMESTAMP.formatValue(t.getDate());
    }

    public static String printUser(Ticket t) {
        return t.getUser()== null ? "" : t.getUser().getName();
    }

    public static String printCustomer(Ticket t) {
        return t.getCustomer()== null ? "" : t.getCustomer().getName();
    }

    public static String printArticlesCount(Ticket t) {
        return Formats.DOUBLE.formatValue(getArticlesCount(t));
    }

    public static String printSubTotal(Ticket t) {
        return Formats.CURRENCY.formatValue(new Double(getSubTotal(t)));
    }

    public static String printPrefArticlesCount(Ticket t) {
        return Formats.INT.formatValue(new Integer(getPrefArticlesCount(t)));
    }

    public static String printPrefSubTotal(Ticket t) {
        return Formats.CURRENCY.formatValue(new Double(getPrefSubTotal(t)));
    }

    public static  String printTax(Ticket t) {
        return Formats.CURRENCY.formatValue(new Double(getTax(t)));
    }

    public static String printTotal(Ticket t) {
        return Formats.CURRENCY.formatValue(new Double(getTotal(t)));
    }

    public static String printTotalPaid(Ticket t) {
        return Formats.CURRENCY.formatValue(new Double(getTotalPaid(t)));
    }

    public static String printPriceRate(Ticket t) {
        return Formats.PERCENT.formatValue(t.getM_dPriceRate());
    }

        public static String printDefSubTotal(Ticket t) {
        return Formats.CURRENCY.formatValue(new Double(getDefSubTotal(t)));
    }

    public static String printDefTax(Ticket t) {
        return Formats.CURRENCY.formatValue(new Double(getDefTax(t)));
    }

    public static String printDefTotal(Ticket t) {
        return Formats.CURRENCY.formatValue(new Double(getDefTotal(t)));
    }

    public static  double getDefSubTotal(Ticket t) {
        double sum = 0.0;
        for (TicketLine line : t.getLines()) {
            sum =RoundUtils.add(sum, TicketLineHelper.getDefSubValue(line));
        }
        return sum;
    }

    public static double getDefTax(Ticket t) {
        double sum = 0.0;
        for (TicketLine line : t.getLines()) {
            sum =RoundUtils.add(sum, TicketLineHelper.getDefTax(line));
        }
        return sum;
    }

    public static double getDefTotal(Ticket t) {
        return RoundUtils.add(getDefSubTotal(t) , getDefTax(t));
    }


    public static IncludeTaxs[] getTaxLines(Ticket t) {

        Map<String, IncludeTaxs> m = new HashMap<String, IncludeTaxs>();

        TicketLine oLine;
        for (Iterator<TicketLine> i = t.getLines().iterator(); i.hasNext();) {
            oLine = i.next();

            IncludeTaxs tx = m.get(oLine.getTaxInfo().getId());
            if (tx == null) {
                tx = new IncludeTaxs(oLine.getTaxInfo());
                m.put(tx.getTaxInfo().getId(), tx);
            }
            tx.add(TicketLineHelper.getSubValue(oLine));
        }

        // return dSuma;
        Collection<IncludeTaxs> avalues = m.values();
        return avalues.toArray(new IncludeTaxs[avalues.size()]);
    }

    public static double getArticlesCount(Ticket t) {
        double dArticles = 0.0;
        TicketLine oLine;

        for (Iterator<TicketLine> i = t.getLines().iterator(); i.hasNext();) {
            oLine = i.next();
            dArticles =RoundUtils.add(dArticles, oLine.getMultiply());
        }

        return dArticles;
    }

    public static int getPrefArticlesCount(Ticket t) {
        int prepCount = 0;
        TicketLine oLine;

        for (Iterator<TicketLine> i = t.getLines().iterator(); i.hasNext();) {
            oLine = i.next();
            if (oLine.isIsPrefSell()) {
                prepCount += oLine.getMultiply();
            }
        }
        return prepCount;
    }

    public static double getPrefSubTotal(Ticket t) {
        double sum = 0.0;
        for (TicketLine line : t.getLines()) {
            if (line.isIsPrefSell()) {
                sum =RoundUtils.add(sum, TicketLineHelper.getPrefSubValue(line));
            }
        }
        return sum;
    }

    public static double getSubTotal(Ticket t) {
        double sum = 0.0;
        for (TicketLine line : t.getLines()) {
            sum =RoundUtils.add(sum, TicketLineHelper.getSubValue(line));
        }
        return sum;
    }

    public static double getTax(Ticket t) {

        double sum = 0.0;
        if (t.hasTaxesCalculated()) {
            for (IncludeTaxs tax : t.getTaxes()) {
                sum =RoundUtils.add(sum, tax.getTax()); // Taxes are already rounded...
            }
        } else {
            for (TicketLine line : t.getLines()) {
                sum =RoundUtils.add(sum, TicketLineHelper.getTax(line));
            }
        }
        return sum;
    }

    public static double getTotal(Ticket t) {

        return RoundUtils.add(getSubTotal(t) , getTax(t));
    }

    public static double getTotalPaid(Ticket t) {
        double sum = 0.0;
        for (PaymentInfo p : t.getPayments()) {
            if (!"debtpaid".equals(p.getName())) {
                sum =RoundUtils.add(sum, p.getTotal());
            }
        }
        return sum;
    }

    public static IncludeTaxs getTaxLine(Ticket t,Tax tax) {

        for (IncludeTaxs taxline : t.getTaxes()) {
            if (tax.getId().equals(taxline.getTaxInfo().getId())) {
                return taxline;
            }
        }
        return new IncludeTaxs(tax);
    }

    public static String getTransactionID(Ticket t) {
        return (t.getPayments().size() > 0)
                ? (t.getPayments().get(t.getPayments().size() - 1)).getTransactionID()
                : StringUtils.getCardNumber(); //random transaction ID
    }

    public static  String getReturnMessage(Ticket t) {
        return ((t.getPayments().get(t.getPayments().size() - 1)) instanceof PaymentInfoMagcard)
                ? ((PaymentInfoMagcard) (t.getPayments().get(t.getPayments().size() - 1))).getReturnMessage()
                : LocalRes.getIntString("button.ok");
    }


    public static void writeExternal(Ticket t,ObjectOutput out) throws IOException {
        // esto es solo para serializar tickets que no estan en la bolsa de tickets pendientes
        out.writeObject(t.m_sId);
        out.writeInt(t.ticketType);
        out.writeInt(t.m_iTicketId);
        out.writeObject(t.m_Customer);
        out.writeObject(t.m_dDate);
        out.writeObject(t.attributes);
        out.writeObject(t.m_aLines);
        out.writeDouble(t.m_dPriceRate);
        out.writeObject(t.m_sGroupName);
        out.writeDouble(t.getTotalScore());
    }

    public static void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        // esto es solo para serializar tickets que no estan en la bolsa de tickets pendientes
        Ticket t=new Ticket();
        t.m_sId = (String) in.readObject();
        t.ticketType = in.readInt();
        t.m_iTicketId = in.readInt();
        t.m_Customer = (Customer) in.readObject();
        t.m_dDate = (Date) in.readObject();
        t.attributes = (HashMap) in.readObject();
        t.m_aLines = (List<TicketLine>) in.readObject();
        t.m_dPriceRate=in.readDouble();
        t.m_sGroupName=(String)in.readObject();

        t.setTotalScore(in.readDouble());
        t.m_User = null;
        t.m_sActiveCash = null;

        t.payments = new ArrayList<PaymentInfo>();
        t.taxes = null;
    }

	public static double getTotalConsultCost(Ticket ticket) {
		double sum = 0.0;
        for (TicketLine line : ticket.getLines()) {
            sum =RoundUtils.add(sum, TicketLineHelper.getConsultCost(line));
        }
        return sum;
	}

	public static String printTotalScore(Ticket t) {
		return Formats.DOUBLE.formatValue(t.getTotalScore());
	}

	public static double getTotalScore(Ticket ticket) {
		double sum = 0.0;
        for (TicketLine line : ticket.getLines()) {
            sum =RoundUtils.add(sum, TicketLineHelper.getScore(line));
        }
        return sum;
	}
}
